$NG.AllReady(function (
	page,
	{
		useValuesChange,
		useClick,
		useUpdateRow,
		useUpdateRows,
		useDataIndexChange,
		useBeforeClick,
	}
) {
	let Flag = false;
	var mstform = $NG.getCmpApi("p_form_zzcp_outbount_m");
	var dgrid = $NG.getCmpApi("p_form_zzcp_outbount_d"); //获取表体数据
	let user = $NG.getUser();

	const gridToolbar = $NG.getCmpApi("toolbar_p_form_zzcp_outbount_d");
	gridToolbar.getItem("imp").setProps({ children: "引用设备清单明细" });

    // const saveBtn = ["save","check","verify"]
    // saveBtn.forEach(item=>{
    //     useBeforeClick(()=>{
    //         return saveIsError()
    //     },item)
    // })

    useBeforeClick(()=>{
        const phone = mstform.getItem("u_sl_phone").getValue()
        const regex = /^1[3-9]\d{9}$/;
        if(!regex.test(phone)){
            $NG.alert("收料人手机号输入有误！")
        }
        if(window._catch_saveLock){
             $NG.alert("当前项目没有厂库，请创建！")
             return false
        }
        return regex.test(phone);
    },"save")
    
    useBeforeClick(()=>{
        const phone = mstform.getItem("u_sl_phone").getValue()
        const regex = /^1[3-9]\d{9}$/;
        if(!regex.test(phone)){
            $NG.alert("收料人手机号输入有误！")
        }
        if(window._catch_saveLock){
             $NG.alert("当前项目没有厂库，请创建！")
             return false
        }
        return regex.test(phone);
    },"check")

    function saveIsError(){
        //校验信号机SC
        const rows1 = dgrid.getData()
        const error = rows1.reduce((value,item,index)=>{
            if(item.u_item_no_EXName && item.u_item_no_EXName.includes("信号机SC")){
                value.push(index+1)
            }
            return value
        },[])
        if(error.length >1){
            $NG.alert("申请明细中不准出现2条或2条以上的 “信号机SC” 名称的物料！")
            return false
        } else {
            return true
        }
    }

	{
		/**
		 *@author 崔赛豪
		 * @description 保存数据处理数据 多层封装方便以后扩展其他功能 保证容错率 不要动
		 * @param {string} k key
		 * @param {any} v value
		 * @param {any} t type
		 */
		function saveData(k, v) {
			localStorage.setItem(k, JSON.stringify(v));
		}

		function getData(k) {
			const storedValue = localStorage.getItem(k);
			if (storedValue) {
				return JSON.parse(storedValue);
			}
			return null;
		}
		function clearData(k) {
			localStorage.removeItem(k);
		}
		function AsyncTypeData(k, t, v) {
			switch (t) {
				case "save":
					saveData(k, v);
					break;
				case "get":
					getData(k);
					// console.log(getData(k), "getData(k)");
					break;
				case "clear":
					clearData(k);
					break;
				default:
					console.log("Invalid t");
			}
		}
		AsyncTypeData("ArrData", "get");
		function fun() {
			setTimeout(() => {
				console.log("111111111");
				// if (!Flag) {
				// 	fun();
				// }
				let rows = $NG.getCmpApi("p_form_zzcp_outbount_d").getRows();
				// rows.forEach((item, index) => {
				// 	getData("ArrData").forEach((i, v) => {
				// 		// console.log(i, v, "i", "v");
				// 		// console.log(item, index, "item", "index");
				// 		if (!i.checked && item.u_sbqdbm == i.u_equipment_list_no) {
				// 			dgrid.deleteRows(index); //删除指定行
				// 		} else {
				// 		}
				// 	});
				// });
                rows.forEach((rowItem) => {
                    computedV1(rowItem);
                    computedV2(rowItem);
                });
				dgrid.refreshView();
			}, 300);
		}
		fun();
	}
	let obj;
	/**
	 *@default: 初始化
	 */
	if ($NG.getCmpApi("p_form_zzcp_outbount_m")) {
		// getPtInfoByPhid();
		cntMFilter();

		if (user) {
			console.log(user.userName);
			console.log(user.userID);
			console.log(page.oType);
			
			if (page.oType == 'add') {
				console.log("新增u_ll_person"); //新增 修改 查看 工作流
				$NG.execServer("GetHrInfo", { id: user.userID }, function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas, "GetHrInfo");
					//帮助字段赋值
					$NG.updateState((updater) => {
						// 帮助字段
						updater.data.p_form_zzcp_outbount_m.setProps({
							u_ll_person: {
								value: datas.hrid,
								label: user.userName,
							},
						});
					});
				});
			}
		}
	}
	/**
	 *@license://表头字段变化逻辑END	//表头字段变化逻辑BEGIN
	 */
	 $NG.updateUI((updater) => {
		updater.form.p_form_zzcp_outbount_m.u_sl_person.setProps({
			onBeforeOpen: async () => {
				var phid_pc = $NG.getCmpApi('p_form_zzcp_outbount_m').getItem('phid_pc').getValue();
				if (!phid_pc) {
					$NG.alert("请先选择项目");
					return false;
				} else {
					return true;
				}
			},          
		  clientSqlFilter: `phid_pc = ${mstform.getItem("phid_pc").getValue()}`, //过滤条件
		});
  
	});
	useValuesChange(({ args }) => {
		mstform.getItem("u_cnt_no").setValue(""); //切换项目清楚合同名称
		getPtInfoByPhid();
		cntMFilter();
		$NG.updateUI((updater) => {
			// $NG.getPageUI();
			// 根据组件目录设置路径，可能存在
			// fieldSetForm
			// PCFieldSetPanelGroup[i][field]
			updater.form.p_form_zzcp_outbount_m.u_sl_person.setProps({
				onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi('p_form_zzcp_outbount_m').getItem('phid_pc').getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
				// ...{
				// 	clientSqlFilter: `phid_pc = ${mstform.getItem("phid_pc").getValue()}`, //过滤条件
                // },
			  // hidden: true, //隐藏
			  // required: true, //必输
			  // disabled: true, //只            
			  clientSqlFilter: `phid_pc = ${mstform.getItem("phid_pc").getValue()}`, //过滤条件
			 
			  // placeholder: "请选择", //输入框字段加提示语
			  // data: [{ value: "01", label: "实施外包用工" }], //下拉过滤
			});
	  
		});
        isCalculating()
	}, "p_form_zzcp_outbount_m.phid_pc");
	/**
	 *@license://检测领料人
	 */
	useValuesChange(({ args }) => {
		console.log(args[0].u_ll_person.origin.Dept_Name, "检测领料人");
		console.log(args[0].u_ll_person.origin.Dept, "检测领料人");
		$NG.updateState((updater) => {
			updater.data.p_form_zzcp_outbount_m.setProps({
				u_ll_dept: {
					label: args[0].u_ll_person.origin.Dept_Name,
					value: args[0].u_ll_person.origin.Dept,
				},
			});
		});
	}, "p_form_zzcp_outbount_m.u_ll_person");
	/**
	 *@license://检测收料人
	 */
	useValuesChange(({ args }) => {
		console.log(args[0].u_sl_person.origin.MobileNumber, "检测收料人");
		$NG.updateState((updater) => {
			updater.data.p_form_zzcp_outbount_m.setProps({
				u_sl_phone: args[0].u_sl_person.origin.MobileNumber,
			});
		});
	}, "p_form_zzcp_outbount_m.u_sl_person");
	/**
	 *@license:监听服务于工程表 1.累计分包金额
	 */

	useUpdateRows(({ args }) => {
		args[0].forEach(async (element, index) => {});
	}, "p_form_zzcp_outbount_d");
	/**
	 *@function:带出项目信息
	 */
	function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
                    console.log(datas);
                    
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_zzcp_outbount_m.setProps({
							// u_supply_att: datas.u_supply_att, //计划完工日期
							// u_supply_name: datas.u_supply_name, //计划竣工日期
							u_pc_name: datas.pc_no, //项目编码
							phid_org: {
								//事业部or组织
								value: datas.org_phid,
								label: datas.org_name,
							},
							u_regional_center: {
								//区域中心
								value: datas.regional_center_phid,
								label: datas.regional_center_name,
							},
							u_product_line: {
								//产品线
								value: datas.midwife_phid,
								label: datas.midwife_name,
							},
							u_division: {
								//事业部
								value: datas.division_phid,
								label: datas.division_name,
							},
						});
					});
				}
			);
			$NG.execServer(
				"getPtInfo2",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
                    console.log(datas);
					let u_pc_tqsg1 = ''
                    if (datas.u_pc_tqsg == 1) {
						u_pc_tqsg1 = 1
					}else{
						u_pc_tqsg1 = 2
					}
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_zzcp_outbount_m.setProps({
							// u_supply_att: datas.u_supply_att, //计划完工日期
							// u_supply_name: datas.u_supply_name, //计划竣工日期
							u_pc_tqsg: u_pc_tqsg1, //项目编码
							// u_xmywlx: datas.user_ywlx,
							u_xmywlx: {
								value: datas.user_ywlx,
								label: datas.c_name,
							},
						});
					});
				}
			);
		}
	}
	/**
	 *@function:过滤项目
	 */
	function cntMFilter() {
		$NG.updateUI((updater, state) => {
			console.log(
				$NG.getCmpApi("p_form_zzcp_outbount_m").getItem("phid_pc").getValue(),
			);

			updater.form.p_form_zzcp_outbount_m.u_cnt_no.setProps({
				onBeforeOpen: async () => {
					var phid_pc = $NG
						.getCmpApi("p_form_zzcp_outbount_m")
						.getItem("phid_pc")
						.getValue();
					if (!phid_pc) {
						$NG.alert("请先选择项目");
						return false;
					} else {
						return true;
					}
				},
				...(!!$NG
					.getCmpApi("p_form_zzcp_outbount_m")
					.getItem("phid_pc")
					.getValue() && {
					clientSqlFilter: {
						bill_type: 1,
						phid_pc: $NG
							.getCmpApi("p_form_zzcp_outbount_m")
							.getItem("phid_pc")
							.getValue(),
					},
				}),
			});
		});
	}
	/**
	 *@license:带出订单编号
	 */
	useValuesChange(({ args }) => {
		console.log(args[0]);
		$NG.updateState((updater) => {
			updater.data.p_form_zzcp_outbount_m.setProps({
				u_cnt_name: args[0].u_cnt_no.origin.bill_no,
				u_cnt_type: {
					label: args[0].u_cnt_no.origin.htlx_name,
					value: args[0].u_cnt_no.origin.cnt_type,
				},
			});
		});
	}, "p_form_zzcp_outbount_m.u_cnt_no");

	useUpdateRows(({ args }) => {
		console.log(args[0]);

		args[0].forEach((rowItem) => {
			computedV1(rowItem);
			computedV2(rowItem);
		});
		dgrid.refreshView();
	}, "p_form_zzcp_outbount_d");
	useUpdateRow(({ args }) => {
		computedV1(args[0]);
		computedV2(args[0]);
		dgrid.refreshView();
	}, "p_form_zzcp_outbount_d");

	/**
	 *@function:计算逻辑
	 */

	function computedV1(rowItem) {

        console.log('222222222222');
        
		const record = rowItem;
		console.log(record.u_item_no);
		
		$NG.execServer(
			"getItemInfoZZCP",
			{ phid: record.u_item_no },
			function (res) {
				console.log(res.Code, "res");
				try {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas, "datas");
					record.u_item_bm = datas.code;
					record.u_wlfl = datas.phid_resbs;
					record.u_wlfl_EXName = datas.name;
					record.u_spec = datas.spec;
					record.u_unit = datas.phid_unit;
					record.u_unit_EXName = datas.msname;
					dgrid.refreshView();
				} catch (error) {}
			}
		);
		$NG.execServer(
			"searchBm",
			{ phid: record.u_item_no },
			function (res) {
				console.log(res.Code, "res");
				try {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas, "datas");
					record.u_crm_no = datas.user_crm_no;
					dgrid.refreshView();
				} catch (error) {}
			}
		);

		console.log(
			mstform.getItem("phid_pc").getValue(),
			record.u_item_no,
			1,
			"1111"
		);

		$NG.execServer(
			"getCountZZCP",
			{ p: mstform.getItem("phid_pc").getValue(), i: record.u_item_no },
			function (res) {
				console.log(res.Code, "res");
				console.log(8570000000000022);
				try {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas.u_qty, "datas,getCountZZCP");
					if (!datas.u_qty) {
						record.u_yck_qyt = 0;
					} else {
						record.u_yck_qyt = datas.u_qty;
					}

					dgrid.refreshView();
				} catch (error) {}
			}
		);
	}
	function computedV2(rowItem) {
		const record = rowItem;

		// 提供默认值并确保为数字类型，防止字符串影响计算
		const u_qty = Number(record.u_qty) || 0; // 数量，默认为 0
		const u_prc_vat_fc = Number(record.u_prc_vat_fc) || 0; // 含税单价，默认为 0
		const u_tax_rate = Number(record.u_tax_rate) || 0; // 税率，默认为 0

		// 计算不含税单价
		const u_prc = u_prc_vat_fc / (1 + u_tax_rate);

		// 计算字段值
		const u_amt_vat = u_qty * u_prc_vat_fc; // 价税合计
		const u_amt = u_qty * u_prc; // 不含税金额
		const u_tax_amt = u_amt_vat - u_amt; // 税额
		const u_amt_vat_fc = u_amt_vat; // 价税合计（与 u_amt_vat 相同）

		// 更新 record 对象
		Object.assign(record, {
			u_prc,
			u_amt_vat,
			u_amt,
			u_tax_amt,
			u_amt_vat_fc,
		});
	}

    // 判断有没有厂库
    (page.oType == 'add' || page.oType == 'edit') && isCalculating()
    function isCalculating(){
        const pc = mstform.getItem("phid_pc").getValue()
        $NG.execServer("getCkByPhidPc",{pc},(res)=>{
            if(res.count == 0) {
                window._catch_saveLock = true
                $NG.alert("该项目下没有厂库，您将无法保存请创建！")
            } else {
                window._catch_saveLock = false
            }
        })
    }
});
// getItemInfoZZCP; 物料查询sql使用
